package org.afk.tools.log;

import java.util.concurrent.*;

public class StopWatch
{
	private final Long start;
	private Long sum;

	public StopWatch()
	{
		this.start = System.nanoTime();
	}

	private long add(final StringBuilder builder, final long nanosSinceStart, final TimeUnit timeUnit)
	{
		final long value = timeUnit.convert(nanosSinceStart, TimeUnit.NANOSECONDS);
		if (value > 0)
		{
			builder.append(value).append(" ").append(timeUnit.toString()).append(" ");
			return nanosSinceStart - TimeUnit.NANOSECONDS.convert(value, timeUnit);
		}
		return nanosSinceStart;
	}

	private long getNanosSinceStart()
	{
		if (this.sum != null)
			return this.sum.longValue() + getPassedNanos();
		else
			return getPassedNanos();
	}

	private long getPassedNanos()
	{
		if (this.start != null)
			return System.nanoTime() - this.start.longValue();
		return 0;
	}

	public void pause()
	{
		if ((this.sum == null))
			this.sum = getPassedNanos();
		else
			this.sum += getPassedNanos();
	}

	@Override
	public String toString()
	{
		final StringBuilder builder = new StringBuilder();
		long xxx = getNanosSinceStart();
		xxx = add(builder, xxx, TimeUnit.DAYS);
		xxx = add(builder, xxx, TimeUnit.HOURS);
		xxx = add(builder, xxx, TimeUnit.MINUTES);
		xxx = add(builder, xxx, TimeUnit.SECONDS);
		xxx = add(builder, xxx, TimeUnit.MILLISECONDS);
		return builder.toString();
	}

}
